package com.zhijiaoyun.controller;

import com.zhijiaoyun.aliyun.oss.OSSManager;
import com.zhijiaoyun.common.*;
import com.zhijiaoyun.controller.base.BaseController;
import com.zhijiaoyun.log.SystemLog;
import com.zhijiaoyun.model.BuyHistory;
import com.zhijiaoyun.model.Course;
import com.zhijiaoyun.model.CourseCategory;
import com.zhijiaoyun.model.Lesson;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author shisfish
 * @date 2017/6/6
 */
@Controller
@RequestMapping(value = "course", produces = "application/json; charset=utf-8")
public class CourseController extends BaseController {

    @ResponseBody
    @RequestMapping(value = "/addCourse", method = RequestMethod.POST)
    @SystemLog(function = "addCourse", description = "添加课程")
    public Map<String, Object> addCourse(String name, String title, Integer status, String categoryIds,
                                         BigDecimal defaultPrice, BigDecimal currentPrice, Integer maturity, String content, String teacherIds,
                                         String marks, @RequestParam("picture") MultipartFile picture, HttpServletRequest request) {
        Map<String, Object> map = new HashedMap<>();
        String createUser = String.valueOf(request.getAttribute(Constant.CREATE_USER));
        Course course = courseService.getCourseByName(name);
        if (course != null) {
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_COURSE_NAME_EXIST);
            map.put(DsConstant.CODE, DsConstant.CODE_COURSE_NAME_EXIST);
            return map;
        }

        // 图片上传地址
        String pictureStr = "";
        if (picture != null && !picture.isEmpty()) {
            pictureStr = FileUtils.saveCoursePicture(picture);
            if ("".equals(pictureStr)) {
                map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_PICTURE_NOT_NULL);
                map.put(DsConstant.CODE, DsConstant.CODE_PICTURE_NOT_NULL);
                return map;
            }
        }

        course = new Course(name, title, pictureStr, status, categoryIds, defaultPrice, currentPrice, maturity, content,
                teacherIds, marks, createUser);
        courseService.addCourse(course);

        // 获得上一个对象
        course = courseService.getCourseByName(name);

        // 添加到课程分类关系表
        reCourseCategoryService.addRECourseCategory(course.getCourseId(), categoryIds);

        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/{courseId}/modifyCourse", method = RequestMethod.POST)
    @SystemLog(function = "modifyCourse", description = "修改课程信息")
    public Map<String, Object> modifyCourse(@PathVariable("courseId") Long courseId, String name, String title,
                                            Integer status, String categoryIds, BigDecimal defaultPrice, BigDecimal currentPrice, Integer maturity,
                                            String content, String marks, @RequestParam(value = "picture", required = false) MultipartFile picture,
                                            String teacherIds,
                                            HttpServletRequest request) {
        Map<String, Object> map = new HashedMap<>();
        String createUser = String.valueOf(request.getAttribute(Constant.CREATE_USER));
        Course course = courseService.getCourseByCourseId(courseId);
        if (course == null) {
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_COURSE_LOST);
            map.put(DsConstant.CODE, DsConstant.CODE_COURSE_LOST);
            return map;
        }

        if (!StringUtils.isEmptyString(name)) {
            Course temp = courseService.getCourseByNameNotCourseId(courseId, name);
            if (temp != null) {
                map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_COURSE_NAME_EXIST);
                map.put(DsConstant.CODE, DsConstant.CODE_COURSE_NAME_EXIST);
                return map;
            }
            course.setName(name);
        }

        if (!StringUtils.isEmptyString(title)) {
            course.setTitle(title);
        }

        if (status != null) {
            course.setStatus(status);
        }

        if (!StringUtils.isEmptyString(categoryIds)) {
            if (!course.getCategoryIds().equals(categoryIds)) {
                // 如果分类不相等，代表修改过分类，则要修改分类关系表
                course.setCategoryIds(categoryIds);

                reCourseCategoryService.addRECourseCategory(courseId, categoryIds);
            }
        }

        if (defaultPrice != null) {
            course.setDefaultPrice(defaultPrice);
        }

        if (currentPrice != null) {
            course.setCurrentPrice(currentPrice);
        }

        if (maturity != null) {
            course.setMaturity(maturity);
            course.setMaturityTime(CommonUtils.addYears(new Date(), maturity));
        }

        if (!StringUtils.isEmptyString(content)) {
            course.setContent(content);
        }

        if (!StringUtils.isEmptyString(marks)) {
            course.setMarks(marks);
        }

        if (StringUtils.isNotEmptyString(teacherIds)) {
            course.setTeacherIds(teacherIds);
        }

        // 图片上传地址
        String pictureStr = "";
        if (picture != null && !picture.isEmpty()) {
        	
        	OSSManager.deleteFile(course.getPicture());
        	
            pictureStr = FileUtils.saveCoursePicture(picture);
            course.setPicture(pictureStr);
        }

        course.setModifyTime(new Date());
        course.setModifyUser(createUser);

        courseService.modifyCourse(course);
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/{courseId}/deleteCourse", method = RequestMethod.POST)
    @SystemLog(function = "deleteCourse", description = "删除课程")
    public Map<String, Object> deleteCourse(@PathVariable("courseId") Long courseId) {
        Map<String, Object> map = new HashMap<>();

        Course course = courseService.getCourseByCourseId(courseId);
        if (course == null) {
            map.put(DsConstant.CODE, DsConstant.CODE_COURSE_LOST);
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_COURSE_LOST);
            return map;
        }

        // 判断有无被购买
        List<BuyHistory> buys = buyHistoryService.getBuyHistoryByGoodsId(1, 1, courseId, 1);
        if (!StringUtils.isEmptyList(buys)) {
            map.put(DsConstant.CODE, DsConstant.CODE_COURSE_DELETE_ERROR_1);
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_COURSE_DELETE_ERROR_1);
            return map;
        }

        List<Lesson> lessons = lessonService.getLessonByCourseId(courseId);
        if (!StringUtils.isEmptyList(lessons)) {
            map.put(DsConstant.CODE, DsConstant.CODE_COURSE_DELETE_ERROR_2);
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_COURSE_DELETE_ERROR_2);
            return map;
        }


        courseService.deleteCourse(course);
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    /**
     * 暂未使用
     *
     * @param courseId
     * @param status
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/{courseId}/{status}/courseStatusChange")
    public Map<String, Object> courseStatusChange(@PathVariable("courseId") Long courseId, Integer status,
                                                  HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        Course course = courseService.getCourseByCourseId(courseId);
        String createUser = String.valueOf(request.getAttribute(Constant.CREATE_USER));
        if (course == null) {
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_COURSE_LOST);
            map.put(DsConstant.CODE, DsConstant.CODE_COURSE_LOST);
            return map;
        }
        course.setStatus(status);

        course.setModifyTime(new Date());
        course.setModifyUser(createUser);

        courseService.modifyCourse(course);

        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    /**
     * 课程列表
     * @param pageIndex
     * @param pageSize
     * @param name
     * @param title
     * @param category1
     * @param category2
     * @param status
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/courses")
    public Map<String, Object> courses(int pageIndex, int pageSize, String name, String title, Long category1, Long category2,
                                          Integer status) {
        pageIndex = setPageIndex(pageIndex);
        pageSize = setPageSize(pageSize, DsConstant.PAGESIZE_DEFAULT);
        return courseService.pageByParamsDto(pageIndex, pageSize, name, title, status, category1, category2);
    }

    /**
     * 课程详情
     *
     * @param courseId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/{courseId}/courseDetail")
    public Map<String, Object> courseDetail(@PathVariable("courseId") long courseId) {
        return courseService.getById(courseId);
    }

    @ResponseBody
    @RequestMapping(value = "addCategory", method = RequestMethod.POST)
    @SystemLog(function = "addCategory", description = "新增课程分类")
    public Map<String, Object> addCategory(String name, Integer status, Long parentId, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String createUser = String.valueOf(request.getAttribute(Constant.CREATE_USER));
        // 同一个父类下没有相同的类别即可
        CourseCategory courseCategory = courseCategoryService.getCourseCategoryByNameParentId(name, parentId);
        if (courseCategory != null) {
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_COURSE_CATEGORY_NAME_EXIST);
            map.put(DsConstant.CODE, DsConstant.CODE_COURSE_CATEGORY_NAME_EXIST);
            return map;
        }

        int level = 2;
        if (parentId == null || parentId == 0) {
            level = 1;
        }

        courseCategory = new CourseCategory(name, parentId, level, status, 1, createUser);

        courseCategoryService.addCategory(courseCategory);
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "{categoryId}/deleteCategory", method = RequestMethod.POST)
    @SystemLog(function = "deleteCategory", description = "删除课程分类")
    public Map<String, Object> deleteCategory(@PathVariable("categoryId") Long categoryId) {
        Map<String, Object> map = new HashMap<>();
        map.put(DsConstant.CODE, "1");
        CourseCategory category = courseCategoryService.getCourseCategoryByCategoryId(categoryId);
        if (category == null) {
            map.put(DsConstant.CODE, DsConstant.CODE_COURSE_CATEGORY_LOST);
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_COURSE_CATEGORY_LOST);
            return map;
        }

        List<Long> categoryids = courseCategoryService.getIdsByParentId(category.getCategoryId());
        if (!StringUtils.isEmptyList(categoryids)) {
            int count = reCourseCategoryService.countByCategoryids(categoryids);
            if (count > 0) {
                map.put(DsConstant.MESSAGE, "分类下已有课程，不能删除");
                return map;
            }
            courseCategoryService.deleteCourseCategoryByParentId(category.getCategoryId());
        }

        int count1 = reCourseCategoryService.countByCategoryId(categoryId);
        if (count1 > 0) {
            map.put(DsConstant.MESSAGE, "分类下已有课程，不能删除");
            return map;
        }

        courseCategoryService.deleteCourseCategory(category);
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "{categoryId}/modifyCategory", method = RequestMethod.POST)
    @SystemLog(function = "modifyCategory", description = "修改课程分类")
    public Map<String, Object> modifyCategory(@PathVariable("categoryId") Long categoryId, String name,
                                              HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String createUser = String.valueOf(request.getAttribute(Constant.CREATE_USER));
        CourseCategory courseCategory = courseCategoryService.getCourseCategoryByCategoryId(categoryId);
        if (courseCategory == null) {
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_COURSE_CATEGORY_LOST);
            map.put(DsConstant.CODE, DsConstant.CODE_COURSE_CATEGORY_LOST);
            return map;
        }

        if (!StringUtils.isEmptyString(name)) {
            CourseCategory temp = courseCategoryService.getCourseCategoryByNameNotCategoryId(name,
                    courseCategory.getParentId(), categoryId);
            if (temp != null) {
                map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_COURSE_CATEGORY_NAME_EXIST);
                map.put(DsConstant.CODE, DsConstant.CODE_COURSE_CATEGORY_NAME_EXIST);
                return map;
            }
            courseCategory.setName(name);
            courseCategory.setModifyTime(new Date());
            courseCategory.setModifyUser(createUser);

            // 只有名称可以改变，若是不该变的话 则不需要进行修改操作
            courseCategoryService.updateCategory(courseCategory);
        }

        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    /**
     * 暂未使用
     *
     * @param categoryId
     * @param status
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "{categoryId}/categoryStatusChange")
    public Map<String, Object> categoryStatusChange(@PathVariable("categoryId") Long categoryId, Integer status,
                                                    HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String createUser = String.valueOf(request.getAttribute(Constant.CREATE_USER));
        CourseCategory courseCategory = courseCategoryService.getCourseCategoryByCategoryId(categoryId);
        if (courseCategory == null) {
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_COURSE_CATEGORY_LOST);
            map.put(DsConstant.CODE, DsConstant.CODE_COURSE_CATEGORY_LOST);
            return map;
        }
        courseCategory.setModifyTime(new Date());
        courseCategory.setModifyUser(createUser);
        courseCategory.setStatus(status);
        courseCategoryService.updateCategory(courseCategory);
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/courseCategoryList")
    public Map<String, Object> courseCategoryList() {
        Map<String, Object> map = new HashMap<>();

        List<CourseCategory> courseCategorys = courseCategoryService.getCourseCategory();
        map.put("list", courseCategorys);
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/{parentId}/getCategory")
    public Map<String, Object> getCategory(@PathVariable("parentId") Long parentId) {
        Map<String, Object> map = new HashMap<>();
        long startTime = System.currentTimeMillis();
        List<CourseCategory> categorys = courseCategoryService.getCourseCategoryByParentId(parentId);
        long endTime = System.currentTimeMillis();
        System.out.println(endTime - startTime);
        map.put("list", categorys);
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }


    /**
     * 未用到
     *
     * @param lessonId
     * @param status
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/{lessonId}/lessonStatusChange")
    public Map<String, Object> lessonStatusChange(@PathVariable("lessonId") Long lessonId, Integer status) {
        Map<String, Object> map = new HashMap<>();
        Lesson lesson = lessonService.getLessonByLessonId(lessonId);
        if (lesson == null) {
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_LESSON_LOST);
            map.put(DsConstant.CODE, DsConstant.CODE_LESSON_LOST);
            return map;
        }
        lesson.setStatus(status);
        lessonService.modifyLesson(lesson);

        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    /**
     * 修改推荐
     *
     * @param courseId
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/{courseId}/changeRecommend")
    @SystemLog(function = "changeRecommend", description = "修改课程推荐")
    public Map<String, Object> changeRecommend(@PathVariable("courseId") long courseId, HttpServletRequest request) {
        String createUser = String.valueOf(request.getAttribute(Constant.CREATE_USER));
        return courseRecommendService.updateRecommend(courseId, createUser);
    }

    /**
     * 推荐列表
     *
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/courseRecommendList")
    public Map<String, Object> courseRecommendList(int pageIndex, int pageSize) {
        if (pageIndex <= 0) {
            pageIndex = 1;
        }
        if (pageSize <= 0) {
            pageSize = DsConstant.PAGESIZE_DEFAULT;
        }
        return courseRecommendService.page(pageIndex, pageSize);
    }

}
